package com.bxd.baodan.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.db.DBHelper;
import com.bxd.baodan.imger.AsyncTaskImageLoad;
import com.bxd.baodan.item.ServiceItem;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.NetUtil;

import java.util.List;

public class ImageService extends Service {

    private List<ServiceItem> list;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        getImgInfo();
    }

    private void loadImage(String url, String fileName) {
        // 异步加载图片资源
        AsyncTaskImageLoad async = new AsyncTaskImageLoad(fileName);
        // 执行异步加载，并把图片的路径传送过去
        async.execute(url);

    }

    /**
     * 获取图片信息
     */
    public void getImgInfo() {

        NetUtil netUtil = new NetUtil(this, JsonApi.IMAGE_SERVICE);
        netUtil.postRequest("",getApplicationContext(), new NetUtil.RequestStringListener() {

            @Override
            public void onComplete(String result) {
                if (JSONUtil.isSuccess(result)) {
                    JsonArray  array = (new Gson().fromJson(result, JsonObject.class)).getAsJsonArray("data");
                    list = new Gson().fromJson(array, new TypeToken<List<ServiceItem>>() {}.getType());

                    if (list != null) {
                        //数据库创建
                        DBHelper.getInstance(getApplicationContext())
                                .initServiceItem(list);  //插入数据库
                        if (list.size()!=0) {
                            for (int i = 0; i < list.size(); i++) {
                                loadImage(list.get(i).getImgUrl(), list.get(i)
                                        .getStartTime()+"_" +list.get(i)
                                        .getEndTime()  + ".jpg");
                            }
                        }

                    }
                } else {
                    Toast.makeText(ImageService.this,
                            JSONUtil.getMessage(result), Toast.LENGTH_SHORT)
                            .show();
                }

            }
        });
    }

}
